<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Mail extends BaseController {

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        $this->admin_init();
        // 用户类型判断
        if($this->userType != USER_TYPE_SCHOOL && $this->userType != USER_TYPE_TEACHER) redirect(admin_url("login"));
        // 加载类库
        $this->load->model('contentModel');
        $this->load->model('schoolModel');
    }

    // 写信
	public function mail_edit($mailId = 0) {
        $this->mailInfo = $mailInfo = $this->contentModel->get_mail_info($mailId);
        if($mailInfo) {
            // 获取收件人列表
            $params['userId'] = $mailInfo['mail_to_user'];
            $userList = $this->schoolModel->get_teacher_list($params);
            $this->mailInfo['toUserName'] = array_value_implode($userList, "realname", "，");
        }

        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "mail". DIRECTORY_SEPARATOR. "mail_edit");
	}
    // 保存邮件
    public function save_mail_action(){
        $mailId = $this->post("id");
        $mailTitle = $this->post("mail_title");
        $mailToUser = $this->post("mail_to_user");
        $mailAttachment = $this->post("mail_attachment");
        $mailContent = $this->post("mail_content", false);
        // 内容检查
        if(!$mailTitle) throw new Exception("请填写邮件标题");
        if(!$mailToUser) throw new Exception("请选择邮件收件人");
        if(!$mailContent) throw new Exception("邮件内容不能为空");
        // 入库
        $data['mail_to_user'] = $mailToUser;
        $data['mail_title'] = $mailTitle;
        $data['mail_attachment'] = $mailAttachment;
        $data['mail_content'] = $mailContent;
        $data['updatetime'] = date("Y-m-d H:i:s");

        if($mailId) {
            // 获取邮件信息
            $mailInfo = $this->contentModel->get_mail_info($mailId);
            $this->check_data_valid($mailInfo, true, true, true, false, $this->rmxUser['id']);

            $this->db->update(ContentModel::$mailTable, $data, "id='{$mailId}'");
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['user_id'] = $this->rmxUser['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(ContentModel::$mailTable, $data);
        }
        // 返回值
        $msg = $mailId ? '修改邮件成功' : '发送邮件成功';
        exit(json($msg, true));
    }
    // 已发送的邮件
    public function send(){
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "mail". DIRECTORY_SEPARATOR. "send");
    }
    // 获取邮件列表
    public function get_send_mail(){
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['userId'] = $this->rmxUser['id'];
        $totalParams['isDelete'] = 0;
        $total = $this->contentModel->get_mail_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['userId'] = $this->rmxUser['id'];
        $data['isDelete'] = 0;
        $mailList = $this->contentModel->get_mail_list($data);
        foreach($mailList as &$mail) {
            $mail['hasAttachment'] = 0;
            if($mail['mail_attachment']) {
                $mail['hasAttachment'] = count(json_decode($mail['mail_attachment']), true);
            }
            
        }

        // 返回值
        exit(admin_table_data($total, $mailList));
    }
    // 获取邮件收件人列表
    public function get_mail_user(){
        $mailId = $this->get("id");
        $mailInfo = $this->contentModel->get_mail_info($mailId);
        // 返回值
        $ret = array();
        // 获取收件人列表
        $params['isDelete'] = 0;
        $params['userId'] = $mailInfo['mail_to_user'];
        $teacherList = $this->schoolModel->get_teacher_list($params);

        foreach($teacherList as $teacher) {
            $tData['name'] = $teacher['realname'];
            $tData['image'] = $teacher['headimgurl'];
            $ret[] = $tData;
        }

        exit(json("", true, $ret));
    }

    // 删除邮件
    public function delete_mail_action(){
        $mailId = $this->post("id");
        $mailInfo = $this->contentModel->get_mail_info($mailId);
        if($mailInfo['user_id'] != $this->rmxUser['id']) throw new Exception("邮件不存在，请刷新后重试");

        // 执行删除操作
        $save['is_delete'] = 1;
        $this->db->update(ContentModel::$mailTable, $save, "id='{$mailId}'");
        exit(json("删除成功", true));
    }

    // 获取邮件详情
    public function mail_info($mailId){
        $this->mailInfo = $mailInfo = $this->contentModel->get_mail_info($mailId);
        // 检查邮件是否存在
        if(!$mailInfo || $mailInfo['is_delete']) show_error("邮件不存在，请返回后重试");
        // 获取邮件收件人
        $toUserArray = explode(",", $mailInfo['mail_to_user']);
        if($mailInfo['user_id'] != $this->rmxUser['id'] && !in_array($this->rmxUser['id'], $toUserArray)) show_error("邮件不存在，请返回后重试");
        // 获取邮件发件人
        $this->sendUser = $this->schoolModel->get_school_user_info($mailInfo['user_id']);
        // 获取附件
        $this->attachment = json_decode($mailInfo['mail_attachment'], true);
        
        $this->menuLink = $this->get("menu_link");
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "mail". DIRECTORY_SEPARATOR. "mail_info");
    }

    // 获取收件箱
    public function index(){
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "mail". DIRECTORY_SEPARATOR. "index");
    }
    // 获取收件邮件列表
    public function get_mail_list(){
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['toUser'] = $this->rmxUser['id'];
        $totalParams['isDelete'] = 0;
        $total = $this->contentModel->get_mail_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['toUser'] = $this->rmxUser['id'];
        $data['isDelete'] = 0;
        $mailList = $this->contentModel->get_mail_list($data);
        foreach($mailList as &$mail) {
            $mail['hasAttachment'] = count(json_decode($mail['mail_attachment']), true);
        }

        // 返回值
        exit(admin_table_data($total, $mailList));
    }
}